package com.abbas.myviewtest.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.abbas.myviewtest.App;
import com.abbas.myviewtest.activity.base.BaseActivity;
import com.abbas.myviewtest.entity.Record;
import com.abbas.myviewtest.view.MyView1;
import com.abbas.myviewtest.view.listener.OnView1Listener;
import com.abbas.myviewtest.view.listener.OnViewGeneratorListener;
import com.abbas.myviewtest.R;
import com.abbas.myviewtest.view.utils.ViewGenerator;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import org.xutils.ex.DbException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GameActivity extends BaseActivity {

    private MyView1 myView1;
    private EditText et;
    private Button bt;
    private TextView tvStep;

    private int rowSize = 4;
    private int columnSize = 4;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private long startTime;
    private long endTime;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_game;
    }

    @Override
    protected void init() {
        initData();
        initView();
        initEvent();
    }

    private void initView() {
        myView1 = (MyView1) findViewById(R.id.myView1);
        et = (EditText) findViewById(R.id.et);
        bt = (Button) findViewById(R.id.bt);
        tvStep = (TextView) findViewById(R.id.tvStep);

        tvStep.setText("已使用步数:0");
    }

    private void initData() {
        generatorViewData();
    }

    private void initEvent() {
        myView1.setListener(new OnView1Listener() {
            @Override
            public void onViewResorted() {
                tvStep.setText("已使用步数:0");
                startTime = System.currentTimeMillis();
            }

            @Override
            public void onChildViewMoved(int[][] childNumber) {
                for (int[] ints : childNumber) {
                    for (int anInt : ints) {
                        Log.e("t",anInt+"\t");
                    }
                }
            }

            @Override
            public void onStepAdded(int step) {
                tvStep.setText("已使用步数:"+step);
            }

            @Override
            public void onGameOver(int step) {
                endTime = System.currentTimeMillis();
                final String[] avaterPath = new String[1];
                View view = getLayoutInflater().inflate(R.layout.record_score,null,false);
                EditText editText = view.findViewById(R.id.et_name);
                ImageView imageView = view.findViewById(R.id.iv_avater);
                Glide.with(GameActivity.this)
                        .load(R.drawable.ic_avater)
                        .transform(new RoundedCorners(12))
                        .into(imageView);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PictureSelector.create(GameActivity.this)
                                .openSystemGallery(SelectMimeType.TYPE_IMAGE)
                                .setSelectionMode(SelectModeConfig.SINGLE)
                                .forSystemResult(new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(ArrayList<LocalMedia> result) {
                                        avaterPath[0] = result.get(0).getPath();
                                        Glide.with(GameActivity.this)
                                                .load(avaterPath)
                                                .transform(new RoundedCorners(12))
                                                .into(imageView);
                                    }

                                    @Override
                                    public void onCancel() {
                                        showToast("取消选择头像");
                                    }
                                });
                    }
                });
                AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this)
                        .setTitle("恭喜过关")
                        .setMessage("Place input your name:")
                        .setView(view)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String name = editText.getText().toString().trim();
                                Record record = new Record();
                                record.setStep(step);
                                if (!TextUtils.isEmpty(name)){
                                    record.setName(name);
                                }else {
                                    record.setName("Anonymous user");
                                }
                                if (!TextUtils.isEmpty(avaterPath[0])){
                                    record.setAvater(avaterPath[0]);
                                }else {
                                    record.setAvater("");
                                }
                                record.setCreateTime(sdf.format(new Date()));
                                record.setFactorial(rowSize);
                                record.setUsingTime((endTime - startTime)/1000/60);
                                try {
                                    App.dbManager.save(record);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            }
                        })
                        .create();
                alertDialog.show();
            }
        });

        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int rowAndColumn = Integer.parseInt(et.getText().toString());
                    if(rowAndColumn < 2 || rowAndColumn > 7){
                        final AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this)
                                .setMessage("换个参数试试")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .create();
                        alertDialog.show();
                    }else {
                        rowSize = rowAndColumn;
                        columnSize = rowAndColumn;
                        myView1.invalidateRowAndColumn(rowSize, columnSize);
                        generatorViewData();
                    }
                    et.setText("");
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    et.setText("");
                }
            }
        });
    }

    private void generatorViewData(){
        ViewGenerator viewGenerator = new ViewGenerator(rowSize, columnSize, new OnViewGeneratorListener() {
            @Override
            public void onStartGenerate() {//即将开始打乱

            }

            @Override
            public void onGenerated(int[][] childViewNumber) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        List<Integer> sortedNumbers = new ArrayList<>();
                        for (int i = 0; i < rowSize; i++) {
                            for (int i1 = 0; i1 < columnSize; i1++) {
                                sortedNumbers.add(childViewNumber[i][i1]);
                            }
                        }
                        Log.e("sortedNumbersCount",sortedNumbers.size()+"");
                        myView1.ResortView(sortedNumbers);
                    }
                });
            }
        });
        new Thread(viewGenerator::startGenerator).start();
    }

    private Handler handler = new Handler();

    @Override
    public boolean onCreateOptionsMenu(@NonNull Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.game_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()){
            case R.id.tow:
                rowSize = 2;
                columnSize = 2;
                break;
            case R.id.three:
                rowSize = 3;
                columnSize = 3;
                break;
            case R.id.four:
                rowSize = 4;
                columnSize = 4;
                break;
            case R.id.five:
                rowSize = 5;
                columnSize = 5;
                break;
            case R.id.six:
                rowSize = 6;
                columnSize = 6;
                break;
            default:
                myView1.invalidateRowAndColumn(rowSize, columnSize);
                generatorViewData();
                break;
        }
        return true;
    }
}